#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>
#include "Log.hpp"
#include "Comm.hpp"
#include "nocopy.hpp"
#include <signal.h>

const static int default_num = 5;

class TcpServer : public nocopy
{
public:
    TcpServer(const uint16_t port)
        : _port(port), _isRunning(false)
    {
    }

    void Init()
    {
        // 1.创建listensocket
        _listenSocket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenSocket < 0)
        {
            lg.LogMessage(Fatal, "_listensocket creat failure errno:%d strerr:%s\n",
                          errno, strerror(errno));
            exit(Socket_Err);
        }
        // 解决一些bind失败的问题，进行socket选项配置
        int opt = 1;
        setsockopt(_listenSocket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        lg.LogMessage(Debug, "create socket success, sockfd: %d\n", _listenSocket);

        // 2.bind
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        int n = bind(_listenSocket, CONV(&local), sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind failure errno:%d strerr:%s\n",
                          errno, strerror(errno));
            exit(Bind_Err);
        }

        // 3. listen
        int l = listen(_listenSocket, default_num);
        if (l != 0)
        {
            lg.LogMessage(Warning, "listen Failure\n");
        }
        lg.LogMessage(Debug, "Listen success\n");
    }

    void Server(int socket)
    {
        char inbuffer[1024];
        // 长服务
        while (_isRunning)
        {
            int n = read(socket, inbuffer, sizeof(inbuffer) - 1);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << "client say#:" << inbuffer << std::endl;
                std::string response = "server say#:";
                response += inbuffer;
                write(socket, response.c_str(), response.size());
            }
            else if (n == 0)
            {
                lg.LogMessage(Warning, "client quit\n");
                return;
            }
            else
            {
                lg.LogMessage(Error, "read failure\n");
                return;
            }
        }
    }

    void Start()
    {
        _isRunning = true;
        while (_isRunning)
        {
            signal(SIGCHLD, SIG_IGN);
            // 4.连接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int socket = accept(_listenSocket, (struct sockaddr *)&(peer), &len);
            if (socket < 0)
            {
                lg.LogMessage(Warning, "accept socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                continue;
            }
            lg.LogMessage(Debug, "accept success, get n new sockfd: %d\n", socket);
            // v1
            // Server(socket);
            // close(socket);
            // v2 - 1 多进程版本--- 父waip子
            // int id = fork();
            // if (id < 0)
            // {
            //     lg.LogMessage(Warning, "fork failure !\n");
            //     close(socket);
            //     return;
            // }
            // else if (id == 0)
            // {
            //     close(_listenSocket);
            //     // child
            //     if (fork() > 0)
            //         exit(-1);
            //     // 子进程退出，唤醒父进程继续获取连接，孙子进程继续执行后序的服务，变成孤儿，让OS回收。
            //     Server(socket);
            //     close(socket);
            //     exit(0);
            // }
            // // father
            // close(socket);
            // int rid = waitpid(id, nullptr, 0);
            // if (rid == id)
            // {
            //     // do noting
            // }
            // v2 - 2 多进程版本--- signal捕捉
            int id = fork();
            if (id < 0)
            {
                lg.LogMessage(Warning, "fork failure !\n");
                close(socket);
                return;
            }
            else if (id == 0)
            {
                //child
                close(_listenSocket);
                Server(socket);
                close(socket);
                exit(0);
            }
            // father
            close(socket);
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listenSocket;
    bool _isRunning;
};
